package com.example.jetpack.learn

import androidx.paging.PagingSource
import androidx.paging.PagingState

class MyDataSource(private val callback: (Int)-> MutableList<Item>) : PagingSource<Int,Item>() {

    override fun getRefreshKey(state: PagingState<Int, Item>): Int? {

        // anchorPosition: 列表中最近访问的索引，包括占位符
        // closestPageToPosition ：将列表中的索引(包括占位符)强制到页中最近的加载页。

        return state.anchorPosition?.let {
            state.closestPageToPosition(it)?.prevKey?.plus(1) ?: state.closestPageToPosition(it)?.nextKey?.minus(1)
        }

//        return state.anchorPosition?.let { state.closestItemToPosition(it)?.id }

    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Item> {
       return try {
            val pageNumber = params.key ?: 0
            params.loadSize
            params.placeholdersEnabled

            //请求结果
            val response = callback.invoke(pageNumber)

            val prevKey = if (pageNumber > 0) pageNumber -1 else null
            val nextKey = if (response.isNotEmpty()) pageNumber + 1 else null
            //返回结果
            LoadResult.Page(data = response, prevKey = prevKey, nextKey = nextKey)
        } catch (e: Exception){
            LoadResult.Error(e)
        }
    }


}